package controll;

import Utils.JwtUtils;
import entity.SysUser;
import Service.SysUserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
        import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.crypto.password.PasswordEncoder;
import mapper.SysUserMapper;

@RestController
@RequestMapping("/api/sys-user")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    // 1. 新增用户
    @PostMapping("/create")
    public ResponseEntity<String> addSysUser(@RequestBody SysUser sysUser) {
        try {
            sysUserService.addSysUser(sysUser);
            return ResponseEntity.ok("用户创建成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统异常：" + e.getMessage());
        }
    }

    // 2. 修改用户
    @PutMapping("/update")
    public ResponseEntity<String> updateSysUser(@RequestBody SysUser sysUser) {
        try {
            sysUserService.updateSysUser(sysUser);
            return ResponseEntity.ok("用户修改成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统异常：" + e.getMessage());
        }
    }

    // 3. 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteSysUser(@PathVariable Long id) {
        try {
            sysUserService.deleteSysUser(id);
            return ResponseEntity.ok("用户删除成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统异常：" + e.getMessage());
        }
    }

    // 4. 查询所有用户
    @GetMapping("/list")
    public ResponseEntity<List<SysUser>> listAllSysUsers() {
        try {
            List<SysUser> users = sysUserService.listAllSysUsers();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(null);
        }
    }

    // 5. 按ID查询用户
    @GetMapping("/{id}")
    public ResponseEntity<SysUser> getSysUserById(@PathVariable Long id) {
        try {
            SysUser user = sysUserService.getSysUserById(id);
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(null);
        }
    }

    // 6. 按用户名查询用户
    @GetMapping("/username/{username}")
    public ResponseEntity<SysUser> getSysUserByUsername(@PathVariable String username) {
        try {
            SysUser user = sysUserService.getSysUserByUsername(username);
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(null);
        }
    }
    // 7.登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        try {
            // 1. Spring Security 认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.get("username"),
                            loginRequest.get("password")
                    )
            );

            // 2. 认证成功，生成 JWT令牌
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String token = jwtUtils.generateToken(userDetails);

            // 3. 返回响应
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("user", sysUserService.getSysUserByUsername(userDetails.getUsername()));

            return ResponseEntity.ok(response);    //返回成功响应

        } catch (Exception e) {
            // 4. 认证失败返回错误401
            return ResponseEntity.status(401)
                    .body(Map.of("message", "用户名或密码错误"));
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> registerRequest) {
        try {
            // 1. 提取注册参数

            String username = registerRequest.get("username");
            String password = registerRequest.get("password");

            // 2. 校验用户是否已存在
            if (sysUserService.getSysUserByUsername(username) != null) {
                return ResponseEntity.badRequest()
                        .body(Map.of("message", "用户名已存在，请更换"));
            }

            // 3. 密码加密
            String encodedPassword = passwordEncoder.encode(password);

            // 4. 构建用户实体 & 写入数据库
            SysUser sysUser = new SysUser();
            sysUser.setUsername(username);
            sysUser.setPassword(encodedPassword);
            sysUser.setRole("ROLE_USER");
            sysUserMapper.insertSysUser(sysUser);

            // 5. 注册成功
            UserDetails userDetails = sysUserService.loadUserByUsername(username);
            String token = jwtUtils.generateToken(userDetails);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "注册成功");
            response.put("token", token);
            response.put("user", sysUserService.getSysUserByUsername(username));
            return ResponseEntity.ok(response);
        } catch (Exception e) {

            // 捕获异常
            return ResponseEntity.status(500)
                    .body(Map.of("message", "注册失败：" + e.getMessage()));
        }
    }

}